package com.chg.mymvc.servlet;

import com.chg.mymvc.entity.Item;
import com.chg.mymvc.entity.News;
import com.chg.mymvc.service.ItemServiceImpl;
import com.chg.mymvc.service.NewsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/addnews")
public class AddNewsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");


        String title = req.getParameter("title");
        String content = req.getParameter("content");

        String option = req.getParameter("selectedoption");
        System.out.println("option="+option);
        ItemServiceImpl is = new ItemServiceImpl();
        NewsServiceImpl ns = new NewsServiceImpl();
        Item item = is.getNewsidByItemId(option);
        System.out.println("Item:"+item);
        int itemid = item.getId();
        //根据item的id去查item对应的perm

        News news = new News();
        news.setTitle(title);
        news.setContent(content);
        news.setItemid(itemid);


        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.0"); //使用了默认的格式创建了一个日期格式化对象。
        String time = dateFormat.format(date); //可以把日期转换转指定格式的字符串
        try {
            Date parse = dateFormat.parse(time);
            System.out.println(parse);
            news.setCrtime(parse);
            int n = ns.addNews(news);
            if (n > 0) {
                resp.sendRedirect("nmanage.html");
            } else {
                System.out.println("错啦错啦");
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
